import {
  GM_registerMenuCommand,
  GM_unregisterMenuCommand,
  GM_download,
} from "tm";

const pages = new Map<string, string>();
let menuId: number | undefined;
let count = 0;
const downAll = () => {
  count = 0;
  for (const [nam, url] of pages.entries()) {
    count += 1;
    setTimeout(() => {
      GM_download(url, String(nam) + ".webp");
    }, 500 * count);
  }
};
const obs = new MutationObserver((mrs) => {
  for (const mr of mrs) {
    for (const node of mr.addedNodes) {
      if ((node as Element).classList.contains("img-page")) {
        if (node.parentElement?.parentElement)
          pages.set(
            node.parentElement.parentElement.id,
            (node as HTMLImageElement).src,
          );
        if (menuId !== undefined) {
          GM_unregisterMenuCommand(menuId);
          menuId = GM_registerMenuCommand(
            `下载全部 ${String(pages.size)} 页`,
            downAll,
          );
        }
      }
    }
  }
});

setTimeout(() => {
  const pdfs = document.querySelector(".pdf-main")?.childNodes;
  if (pdfs) {
    for (const node of pdfs) {
      const page = (node as Element).querySelector(".img-page");
      if (page instanceof HTMLImageElement) {
        pages.set((node as Element).id, page.src);
        if (menuId) GM_unregisterMenuCommand(menuId);
        menuId = GM_registerMenuCommand(
          `下载全部 ${String(pages.size)} 页`,
          downAll,
        );
      }
    }

    obs.observe(document.querySelector(".pdf-main")!, {
      childList: true,
      subtree: true,
    });
  }
}, 2000);
